<template>
  <div class="scroll-container" ref="container">
    <div
      class="scroll-text"
      :class="{ 'scrolling': shouldScroll && isHovered }"
      ref="text"
    >
      {{ text }}
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'

const props = defineProps({
  text: {
    type: String,
    required: true
  }
})

const container = ref(null)
const text = ref(null)
const isHovered = ref(false)
const shouldScroll = ref(false)

// 判断是否需要滚动
const checkOverflow = () => {
  if (container.value && text.value) {
    shouldScroll.value = text.value.scrollWidth > container.value.clientWidth
  }
}

onMounted(() => {
  checkOverflow()
  window.addEventListener('resize', checkOverflow)
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', checkOverflow)
})

const handleMouseEnter = () => {
  isHovered.value = true
}

const handleMouseLeave = () => {
  isHovered.value = false
}

watch(
  () => props.text,
  () => {
    setTimeout(checkOverflow, 0)
  }
)
</script>

<style lang="scss" scoped>
.scroll-container {
  position: relative;
  overflow: hidden;
  white-space: nowrap;
  width: 100%;
  height: 100%;
}

.scroll-text {
  position: absolute;
  white-space: nowrap;
  font-weight: 500;
  font-size: 18px;
  color: #AA7B3B;

  &.scrolling {
    animation: scrollText 4s linear infinite;
  }
}

@keyframes scrollText {
  0% {
    transform: translateX(0%);
  }
  50% {
    transform: translateX(100%);
  }
  100% {
    transform: translateX(0%);
  }
}
</style>